package com.ylz.sjzx.sio.core;

import com.ylz.sjzx.sio.common.core.enums.SioBalanceType;
import com.ylz.sjzx.sio.core.group.manager.GroupRpc;
import com.ylz.sjzx.sio.core.group.model.CmdMessage;
import com.ylz.sjzx.sio.core.group.model.GroupRegister;
import com.ylz.sjzx.sio.core.rule.AllLoadBalance;
import com.ylz.sjzx.sio.core.rule.ILoadBalancer;
import com.ylz.sjzx.sio.core.rule.RandomLoadBalance;

import java.util.List;

/**
 * Description:
 *
 * @date:2021/9/15
 * @author:wiqi
 */
public class SioRpcService {

    /**
     * 发送cmd 消息
     *
     * @param cmdMessage
     */
    public static void sendCmdMessage(CmdMessage cmdMessage) {
        //根据设置的类型获取正确的均衡器
        ILoadBalancer rightBalance = getRightBalance(cmdMessage.getSioBalance());
        //获取对应实例 发送远程消息
        List<GroupRegister> reachableServers = rightBalance.getReachableServers(cmdMessage);

        for (GroupRegister groupRegister : reachableServers) {
            GroupRpc.sendMessage(groupRegister.getAddr(), cmdMessage);
        }
    }

    /**
     * @param sioBalance
     * @return
     */
    private static ILoadBalancer getRightBalance(SioBalanceType sioBalance) {
        switch (sioBalance) {
            case ALL:
                return AllLoadBalance.instance;
            default:
                return RandomLoadBalance.instance;
        }

    }
}
